<!--
 * @Author: Rain
 * @Date: 2023/09/26 11:37:54
 * @LastEditTime: 2024/01/18 10:34:21
 * @Description: Do Something
-->
<template>
  <div class="app-container w-full h-full overflow-hidden">
    <div class="head-container w-full h-full flex flex-col overflow-hidden">
      <div v-if="crud.props.searchToggle" class="flex items-center flex-end">
        <label class="el-form-item-label">名称</label>
        <el-input
          v-model="query.courseName"
          class="filter-item"
          clearable
          placeholder="名称"
          style="width: 185px"
          @keyup.enter.native="crud.toQuery"
        />
        <label class="el-form-item-label">课程类型</label>
        <el-select v-model="query.platform" filterable placeholder="请选择">
          <el-option
            v-for="item in dict.course_type"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <label class="el-form-item-label">课程分类</label>
        <el-select v-model="query.typeId" placeholder="请选择分类">
          <el-option
            v-for="item in typeList"
            :key="item.typeId"
            :label="item.typeName"
            :value="item.typeId"
          />
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <crudOperation :permission="permission" />
      <div class="w-full flex-1 overflow-hidden">
        <el-table
          ref="table"
          v-loading="crud.loading"
          :data="crud.data"
          size="small"
          style="width: 100%"
          height="100%"
          @selection-change="crud.selectionChangeHandler"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="名称" prop="courseName" />
          <el-table-column label="副标题" prop="subTitle" />
          <el-table-column label="课程类型" prop="platform">
            <template slot-scope="scope">{{
              dict.label.course_type[scope.row.platform]
            }}</template>
          </el-table-column>
          <el-table-column label="课程分类" prop="typeId">
            <template slot-scope="{ row }">{{
              row.typeId | getType(typeList)
            }}</template>
          </el-table-column>
          <el-table-column label="价格" prop="sellPrice" />
          <el-table-column label="优惠价" prop="discountPrice" />
          <el-table-column label="优惠价启停" prop="showDiscount">
            <template slot-scope="{ row }">
              <el-switch
                v-model="row.showDiscount"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="openSwitch($event, 'showDiscount', row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="图标" prop="courseLogo">
            <template slot-scope="{ row }">
              <img
                :src="row.courseLogo | imgTransform"
                alt=""
                style="width: 40px; height: 40px"
              >
            </template>
          </el-table-column>
          <el-table-column label="横幅图" prop="courseBanner">
            <template slot-scope="{ row }">
              <img
                :src="row.courseBanner | imgTransform"
                alt=""
                style="width: 40px; height: 40px"
              >
            </template>
          </el-table-column>
          <el-table-column label="上架/下架" prop="status">
            <template slot-scope="{ row }">
              <el-switch
                v-model="row.status"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="openSwitch($event, 'status', row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="排序" prop="sortIndex" />
          <el-table-column label="开班时间" prop="openTime" />
          <el-table-column prop="category" label="课程类别">
            <template slot-scope="scope">{{
              dict.label.course_category[scope.row.category]
            }}</template>
          </el-table-column>
          <el-table-column label="首页展示" prop="showIndex">
            <template slot-scope="{ row }">
              <el-switch
                v-model="row.showIndex"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="openSwitch($event, 'showIndex', row)"
              />
            </template>
          </el-table-column>
          <el-table-column
            v-if="checkPer(['admin', 'courseInfo:edit', 'courseInfo:del'])"
            align="center"
            label="操作"
            width="200px"
            fixed="right"
          >
            <template slot-scope="scope">
              <div class="w-full flex items-center justify-center">
                <el-button
                  type="primary"
                  icon="el-icon-alarm-clock"
                  title="打卡设置"
                  size="mini"
                  style="margin-right: 5px"
                  @click="signAction(scope.row)"
                />
                <udOperation :data="scope.row" :permission="permission" />
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <pagination />
    </div>
    <el-dialog
      :before-close="crud.cancelCU"
      :close-on-click-modal="false"
      :title="crud.status.title"
      :visible.sync="crud.status.cu > 0"
      width="700px"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
        size="small"
      >
        <el-collapse v-model="active" accordion class="w-full">
          <el-collapse-item name="1" title="基本信息">
            <el-row :gutter="20">
              <el-col :offset="0" :span="12">
                <el-form-item label="名称" prop="courseName">
                  <el-input
                    v-model="form.courseName"
                    placeholder="请输入课程名称"
                  />
                </el-form-item>
              </el-col>
              <el-col :offset="0" :span="12">
                <el-form-item
                  label="课程类型"
                  prop="platform"
                  :rules="[
                    { required: true, message: '请选择类型', trigger: 'blur' },
                  ]"
                >
                  <el-select
                    v-model="form.platform"
                    class="w-full"
                    filterable
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in dict.course_type"
                      :key="item.id"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :offset="0" :span="12">
                <el-form-item
                  label="副标题"
                  prop="subTitle"
                  :rules="[
                    {
                      required: true,
                      message: '请输入副标题',
                      trigger: 'blur',
                    },
                  ]"
                >
                  <el-input v-model="form.subTitle" placeholder="请输入..." />
                </el-form-item>
              </el-col>
              <el-col :offset="0" :span="12">
                <el-form-item label="课程类别">
                  <el-select
                    v-model="form.category"
                    filterable
                    placeholder="请选择"
                    class="w-full"
                  >
                    <el-option
                      v-for="item in dict.course_category"
                      :key="item.id"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :offset="0" :span="12">
                <el-form-item
                  label="课程分类"
                  :rules="[
                    { required: true, message: '请选择分类', trigger: 'blur' },
                  ]"
                  prop="typeId"
                >
                  <el-select
                    v-model="form.typeId"
                    class="w-full"
                    placeholder="请选择分类"
                  >
                    <el-option
                      v-for="item in typeList"
                      :key="item.typeId"
                      :label="item.typeName"
                      :value="item.typeId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :offset="0" :span="12">
                <el-form-item
                  label="价格"
                  :rules="[
                    { required: true, message: '请输入价格', trigger: 'blur' },
                  ]"
                  prop="sellPrice"
                >
                  <el-input-number
                    v-model.number="form.sellPrice"
                    class="w-full"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :offset="0" :span="12">
                <el-form-item
                  label="优惠价"
                  :rules="[
                    {
                      required: true,
                      message: '请输入优惠价格',
                      trigger: 'blur',
                    },
                  ]"
                  prop="discountPrice"
                >
                  <el-input-number
                    v-model="form.discountPrice"
                    class="w-full"
                  />
                </el-form-item>
              </el-col>
              <el-col :offset="0" :span="12">
                <el-form-item
                  label="首页展示"
                  :rules="[
                    { required: true, message: '请选择', trigger: 'blur' },
                  ]"
                  prop="showIndex"
                >
                  <el-radio-group v-model="form.showIndex" class="w-full">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :offset="0" :span="12">
                <el-form-item
                  label="开班时间"
                  prop="openTime"
                  :rules="[
                    { required: true, message: '请选择', trigger: 'blur' },
                  ]"
                >
                  <el-date-picker
                    v-model="form.openTime"
                    placeholder="请选择"
                    type="datetime"
                  />
                </el-form-item>
              </el-col>
              <el-col :offset="0" :span="12">
                <el-form-item
                  label="排序"
                  prop="sortIndex"
                  :rules="[
                    { required: true, message: '请输入排序', trigger: 'blur' },
                  ]"
                >
                  <el-input-number v-model="form.sortIndex" class="w-full" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :offset="0" :span="12">
                <el-form-item
                  label="优惠价启停"
                  :rules="[
                    { required: true, message: '请选择', trigger: 'blur' },
                  ]"
                  prop="showDiscount"
                >
                  <el-select
                    v-model="form.showDiscount"
                    class="w-full"
                    filterable
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in dict.discount_use"
                      :key="item.id"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :offset="0" :span="12">
                <el-form-item
                  label="优秀打卡内容"
                  :rules="[
                    { required: true, message: '请选择', trigger: 'blur' },
                  ]"
                  prop="showExcellent"
                >
                  <el-radio-group v-model="form.showExcellent" class="w-full">
                    <el-radio :label="1">显示</el-radio>
                    <el-radio :label="0">隐藏</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :offset="0" :span="12">
                <el-form-item label="图标">
                  <uploadImg
                    ref="uploadLogo"
                    :src="form.courseLogo"
                    @upload="($event) => (form.courseLogo = $event)"
                  />
                </el-form-item>
              </el-col>
              <el-col :offset="0" :span="12">
                <el-form-item label="横幅图">
                  <uploadImg
                    ref="uploadBanner"
                    :src="form.courseBanner"
                    @upload="($event) => (form.courseBanner = $event)"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <el-collapse-item
            v-show="form.platform * 1 === 0"
            name="2"
            title="课程目录"
          >
            <div class="flex items-center flex-end w-full">
              <el-button
                icon="el-icon-plus"
                size="mini"
                type="primary"
                @click="addRecord(1)"
              >添加</el-button>
            </div>
            <el-table :data="form.itemList" class="w-full" fit>
              <el-table-column
                align="center"
                label="#"
                type="index"
                width="60"
              />
              <el-table-column align="center" label="标题" prop="itemTitle" />
              <el-table-column
                align="center"
                label="时长(秒)"
                prop="duration"
              />
              <el-table-column align="center" label="链接" prop="itemValue" />
              <el-table-column align="center" label="操作" width="160">
                <template slot-scope="{ row, $index }">
                  <div clsass="flex items-center w-full">
                    <el-button
                      size="mini"
                      style="margin-right: 4px"
                      type="danger"
                      @click="doAction(row, 1, $index)"
                    >删除</el-button>
                    <el-button
                      size="mini"
                      type="primary"
                      @click="doAction(row, 2)"
                    >查看</el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>
          <el-collapse-item name="3" title="课程详情">
            <el-form-item
              class="w-full"
              label="详细介绍"
              style="grid-column: span 2"
            >
              <Editor ref="editor" :content="form.courseInfo" />
            </el-form-item>
          </el-collapse-item>
        </el-collapse>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="default" @click="crud.cancelCU">取消</el-button>
        <el-button
          :loading="crud.status.cu === 2"
          type="primary"
          @click="submitAction"
        >确认</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :before-close="dialogBeforeClose"
      :visible.sync="dialogVisible"
      title="上传附件"
      width="400px"
    >
      <el-form
        ref="attachForm"
        :model="attach"
        label-position="right"
        label-width="80px"
      >
        <el-form-item
          :rules="[{ required: true, message: '请输入标题', trigger: 'blur' }]"
          label="标题"
          prop="itemTitle"
        >
          <el-input v-model="attach.itemTitle" />
        </el-form-item>
        <el-form-item
          :rules="[{ required: true, message: '请选择', trigger: 'blur' }]"
          label="试看"
          prop="trysee"
        >
          <el-switch
            v-model="attach.trysee"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item
          :rules="[{ required: true, message: '请上传附件', trigger: 'blur' }]"
          label="附件"
          prop="itemValue"
        >
          <UploadFile
            ref="uploadFile"
            :src="attach.itemValue"
            :type="
              form.category * 1 === 1
                ? 'video'
                : form.category * 1 === 2
                  ? 'audio'
                  : 'pdf'
            "
            @upload="uploadVideo"
            @updateTime="($event) => (attach.duration = $event)"
          />
        </el-form-item>
        <el-form-item
          v-if="form.category * 1 !== 3"
          :rules="[
            {
              required: true,
              message: '请输入时长',
              trigger: ['blur', 'change'],
            },
          ]"
          label="时长(秒)"
          prop="duration"
        >
          <div v-text="attach.duration" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button size="mini" @click="dialogBeforeClose">取 消</el-button>
        <el-button
          size="mini"
          type="primary"
          :loading="loading"
          @click="addRecord(2)"
        >确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="打卡设置"
      :visible.sync="signShow"
      :before-close="dialogBeforeClose"
      width="30%"
    >
      <el-form ref="signForm" :model="signRow" label-width="80px" size="normal">
        <el-form-item
          label="打卡权限"
          prop="visibleAuth"
          :rules="[{ required: true, message: '请选择', trigger: 'change' }]"
        >
          <el-select
            v-model="signRow.visibleAuth"
            placeholder="请选择"
            clearable
            class="w-full"
          >
            <el-option label="全员可见" :value="0" />
            <el-option label="班级可见" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item
          label="内容审核"
          prop="requiredAudit"
          :rules="[{ required: true, message: '请选择', trigger: 'change' }]"
        >
          <el-select
            v-model="signRow.requiredAudit"
            placeholder="请选择"
            clearable
            class="w-full"
          >
            <el-option label="不需要" :value="0" />
            <el-option label="需要" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item
          label="开始时间"
          prop="startDate"
          :rules="[{ required: true, message: '请选择', trigger: 'change' }]"
        >
          <el-date-picker
            v-model="signRow.startDate"
            type="date"
            placeholder="请选择"
            class="w-full"
          />
        </el-form-item>
        <el-form-item
          label="结束时间"
          prop="endDate"
          :rules="[{ required: true, message: '请选择', trigger: 'change' }]"
        >
          <el-date-picker
            v-model="signRow.endDate"
            type="date"
            placeholder="请选择"
            class="w-full"
          />
        </el-form-item>
        <!-- <el-form-item
          label="状态"
          prop="status"
          :rules="[{ required: true, message: '请选择', trigger: 'change' }]"
        >
          <el-radio-group v-model="signRow.status">
            <el-radio :label="1">有效</el-radio>
            <el-radio :label="0">无效</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="打卡规则">
          <el-input
            v-model="signRow.clockRule"
            type="textarea"
            class="w-full"
            :rows="4"
          />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialogBeforeClose">取消</el-button>
        <el-button type="primary" @click="signSubmitAction">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import crudCourseInfo, {
  cursorClockCfg,
  getCursorClockCfg
} from '@/api/course'
import crudCourseType from '@/api/courseType'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import uploadImg from '@/components/uploadImage'
import Editor from '@/components/Editor'
import UploadFile from '@/components/uploadFile'
import { debounce } from 'lodash'
import { Message } from 'element-ui'

const defaultForm = {
  courseId: null,
  courseNo: null,
  courseName: null,
  subTitle: null,
  sellPrice: null,
  discountPrice: null,
  courseLogo: null,
  courseBanner: null,
  typeId: null,
  createTime: null,
  createby: null,
  updateTime: null,
  updateby: null,
  category: 1,
  courseInfo: null,
  showIndex: 1,
  openTime: null,
  platform: '0',
  sortIndex: null,
  showDiscount: 1,
  showExcellent: 1,
  itemList: [],
  status: 1
}
export default {
  name: 'CourseInfo',
  components: {
    pagination,
    crudOperation,
    rrOperation,
    udOperation,
    uploadImg,
    Editor,
    UploadFile
  },
  filters: {
    getType(val, typeList) {
      const item = typeList.find((item) => item.typeId === val)
      return item && item.typeName
    }
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: [
    'course_type',
    'discount_use',
    'course_status',
    'course_clock_show',
    'course_category'
  ],
  cruds() {
    return CRUD({
      title: '课程信息',
      url: 'api/courseInfo',
      idField: 'courseId',
      sort: 'courseId,desc',
      crudMethod: { ...crudCourseInfo }
    })
  },
  data() {
    return {
      permission: {
        add: ['admin', 'courseInfo:add'],
        edit: ['admin', 'courseInfo:edit'],
        del: ['admin', 'courseInfo:del']
      },
      rules: {
        courseName: [
          { required: true, message: '请输入课程名称', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'courseName', display_name: '名称' },
        { key: 'typeId', display_name: '分类' },
        { key: 'platform', display_name: '类型' }
      ],
      typeList: [],
      active: '1',
      dialogVisible: false,
      loading: false,
      attach: {
        itemTitle: '',
        itemValue: '',
        trysee: 1,
        duration: 0
      },
      signRow: {
        startDate: '',
        endDate: '',
        visibleAuth: 0,
        requiredAudit: 0,
        status: 1,
        clockRule: ''
      },
      signShow: false
    }
  },
  mounted() {
    crudCourseType.get().then((res) => {
      const { content } = res
      this.typeList = content
    })
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    // 更新前拦截
    [CRUD.HOOK.beforeToCU]() {
      this.active = '1'
      this.form.platform = this.form.platform + ''
      this.form.category = this.form.category + ''
      this.form.showDiscount = this.form.showDiscount + ''
      form(defaultForm)
    },
    // 提交前拦截
    [CRUD.HOOK.beforeSubmit]() {
      const content = this.$refs['editor'].getContent()
      this.form.courseInfo = content
      this.form.category = this.form.category * 1
      if (this.form.platform * 1 === 1) {
        this.form.itemList = []
        this.form['items'] = []
      } else {
        this.form['items'] = this.form.itemList
      }
    },
    [CRUD.HOOK.failValidateCU]() {
      this.active = '1'
    },
    doAction(row, flag, index) {
      if (flag === 1) {
        this.$confirm('确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.form.itemList.splice(index, 1)
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      }
    },
    addRecord(flag) {
      if (flag === 1) {
        this.dialogVisible = true
      } else {
        try {
          this.$refs['attachForm'].validate((valid) => {
            if (valid) {
              this.loading = true
              this.$refs['uploadFile'].handleUpload().then((res) => {
                if (res) {
                  this.attach.itemValue = res
                  if (this.form.courseId) {
                    this.attach.courseId = this.form.courseId
                    this.attach.courseNo = this.form.courseNo
                  }
                  this.form.itemList.push(this.attach)
                  this.dialogVisible = false
                  this.loading = false
                }
              })
            }
          })
        } catch (error) {
          this.loading = false
        }
      }
    },
    dialogBeforeClose() {
      if (this.dialogVisible) {
        this.attach = { itemTitle: '', itemValue: '' }
        this.dialogVisible = false
        this.loading = false
        this.$refs['attachForm'].resetFields()
        this.$refs['attachForm'].clearValidate()
      } else if (this.signShow) {
        this.signRow = {}
        this.$refs['signForm'].clearValidate()
        this.$refs['signForm'].resetFields()
        this.signShow = false
      }
    },
    openSwitch: debounce((val, key, row) => {
      row[key] = val
      crudCourseInfo
        .edit(row)
        .then((_) => {
          Message({
            type: 'success',
            message: '操作成功!'
          })
        })
        .catch((_) => {
          Message({
            type: 'error',
            message: '操作失败!'
          })
        })
    }, 1000),
    signAction(row) {
      const { courseNo, courseName } = row
      getCursorClockCfg({ courseNo }).then((res) => {
        const { content, totalElements } = res
        if (totalElements > 0) {
          const row = content.at(0)
          Object.assign(this.signRow, { ...row })
          this.signShow = true
        } else {
          Object.assign(this.signRow, { courseName, courseNo })
          this.signRow = row
          this.signShow = true
        }
      })
    },
    signSubmitAction() {
      this.$refs['signForm'].validate((valid) => {
        if (valid) {
          cursorClockCfg(this.signRow)
            .then((res) => {
              this.signShow = false
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
            })
            .catch((_) => {
              this.$message({
                type: 'error',
                message: '操作失败!'
              })
            })
        }
      })
    },
    submitAction() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          Promise.all([
            this.$refs['uploadLogo'].handleUpload(),
            this.$refs['uploadBanner'].handleUpload()
          ]).then((res) => {
            this.crud.submitCU()
          })
        }
      })
    },
    uploadVideo(file) {
      this.attach.itemValue = file
    },
    [CRUD.HOOK.afterToEdit]({ form }) {
      console.log(form)
    }
  }
}
</script>

<style scoped lang="scss"></style>
